<template>
  <!-- 甘特图展示区域 -->
  <div style="height: 500px; background-color: white">
    <div id="gantt_here" style="width: 100%; height: 100%"></div>
  </div>

  <!-- 甘特图任务管理对话框 -->
  <el-dialog v-model="ganttDialogVisible" title="甘特图任务管理" width="600px">
    <el-form :model="ganttForm">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="ganttForm.taskName"
          placeholder="请输入任务名称"
          required
        />
      </el-form-item>
      <el-form-item label="工作站" prop="resource">
        <el-input v-model="ganttForm.resource" placeholder="请输入工作站" />
      </el-form-item>
      <el-form-item label="工序" prop="process">
        <el-input v-model="ganttForm.process" placeholder="请输入工序" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="ganttForm.startTime"
          type="datetime"
          placeholder="选择开始时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="['00:00', '23:59']"
          required
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="ganttForm.endTime"
          type="datetime"
          placeholder="选择结束时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="['00:00', '23:59']"
          required
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="ganttDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleGanttSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { gantt } from 'dhtmlx-gantt';
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css';
const apiUrl = import.meta.env.VITE_APP_API_URL;

// 对话框显示控制
const ganttDialogVisible = ref(false); // 甘特图任务管理对话框

// 甘特图相关数据
const ganttForm = reactive({
  productionTaskId: 0,
  taskName: '',
  resource: '',
  process: '', // 新增工序字段
  startTime: '',
  endTime: ''
});
const editingTask = ref(null); // 当前编辑的甘特图任务
const ganttData = ref({ tasks: [], links: [] }); // 甘特图数据

// 获取甘特图任务数据
const fetchGanttData = async () => {
  try {
    const response = await axios.get(apiUrl+'/T5/Setting/Showgtt');
    ganttData.value = {
      tasks: response.data.data.map(task => ({
        productionTaskId: task.productionTaskId,
        taskName: task.taskName,
        resource: task.resource,
        process: task.process, // 新增工序字段获取
        startTime: task.startTime,
        endTime: task.endTime,
        productionOrder: task.productionOrder || '', // 假设后端返回生产工单字段，这里设置默认空字符串
        completionRate: task.completionRate || 0 // 假设后端返回完成比例字段，这里设置默认0
      })),
      links: []
    };
    gantt.parse(ganttData.value);
  } catch (error) {
    console.error('获取甘特图任务数据失败:', error);
    ElMessage.error('获取甘特图任务数据失败');
  }
};

// 打开甘特图任务管理对话框
const openGanttDialog = (task?: any) => {
  ganttDialogVisible.value = true;
  if (task) { // 修改模式
    editingTask.value = task;
    Object.assign(ganttForm, {
      productionTaskId: task.productionTaskId,
      taskName: task.taskName,
      resource: task.resource,
      process: task.process, // 工序字段赋值
      startTime: task.startTime,
      endTime: task.endTime
    });
  } else { // 新增模式
    editingTask.value = null;
    const now = new Date();
    ganttForm.startTime = new Date(now.getTime() + 3600000).toISOString().split('.')[0];
    ganttForm.endTime = new Date(now.getTime() + 7200000).toISOString().split('.')[0];
  }
};

// 提交甘特图任务表单
const handleGanttSubmit = () => {
  if (!ganttForm.taskName || !ganttForm.startTime || !ganttForm.endTime) {
    ElMessage.error('任务名称、开始时间、结束时间为必填项');
    return;
  }

  const taskData = {
    taskName: ganttForm.taskName,
    resource: ganttForm.resource,
    process: ganttForm.process, // 包含工序字段
    startTime: ganttForm.startTime,
    endTime: ganttForm.endTime
  };

  if (editingTask.value) {
    taskData.productionTaskId = editingTask.value.productionTaskId;
    axios.put(apiUrl+'/T6/setting/Updategtt', taskData)
     .then(res => {
        if (res.data.code === 200) {
          ElMessage.success('任务修改成功');
          const index = ganttData.value.tasks.findIndex(task => task.productionTaskId === editingTask.value.productionTaskId);
          if (index!== -1) {
            ganttData.value.tasks[index] = { ...taskData, productionTaskId: editingTask.value.productionTaskId };
            gantt.parse(ganttData.value);
          }
          ganttDialogVisible.value = false;
        } else {
          ElMessage.error('任务修改失败: ' + (res.data.message || '未知错误'));
        }
      })
     .catch(error => {
        console.error('修改任务失败:', error.response? error.response.data : error);
        ElMessage.error('修改任务失败');
      });
  } else {
    axios.post(apiUrl+'/T6/setting/Addgtt', taskData)
     .then(res => {
        if (res.data.code === 200) {
          ElMessage.success('任务添加成功');
          ganttData.value.tasks.push({ ...res.data.task });
          gantt.parse(ganttData.value);
          ganttDialogVisible.value = false;
        } else {
          ElMessage.error('任务添加失败: ' + (res.data.message || '未知错误'));
        }
      })
     .catch(error => {
        console.error('添加任务失败:', error.response? error.response.data : error);
        ElMessage.error('添加任务失败');
      });
  }
  editingTask.value = null;
};

// 删除甘特图任务
const deleteGanttTask = (taskId: number) => {
  axios.delete(apiUrl+'/T6/setting/Delgtt/${taskId}')
    .then(res => {
      if (res.data.code === 200) {
        ElMessage.success('任务删除成功');
        ganttData.value.tasks = ganttData.value.tasks.filter(task => task.productionTaskId!== taskId);
        gantt.parse(ganttData.value);
      } else {
        ElMessage.error('任务删除失败: ' + (res.data.message || '未知错误'));
      }
    })
    .catch(error => {
      console.error('删除任务失败:', error.response? error.response.data : error);
      ElMessage.error('删除任务失败');
    });
};

// 甘特图初始化
onMounted(() => {
  gantt.plugins({ quick_info: true, marker: true, tooltip: true });
  gantt.config.readonly = false;
  gantt.config.lightbox.sections = [];
  gantt.config.drag_move = true;
  gantt.config.auto_types = true;
  gantt.config.open_split_tasks = true;
  gantt.config.xml_date = '%Y.%m.%d %H:%i:%s';
  gantt.config.show_errors = false;
  gantt.ext.zoom.init({
    levels: [
      {
        name: 'day',
        scale_height: 60,
        min_column_width: 18,
        scales: [
          { unit: 'month', format: '%Y-%m' },
          {
            unit: 'day',
            step: 1,
            format: '%d',
            css: (date) => date.getDay() === 0 || date.getDay() === 6? 'day-item weekend weekend-border-bottom' : 'day-item'
          }
        ]
      },
      {
        name: 'week',
        height: 60,
        min_column_width: 110,
        scales: [
          {
            unit: 'quarter',
            step: 1,
            format: (date) => {
              const yearStr = new Date(date).getFullYear() + '年';
              const dateToStr = gantt.date.date_to_str('%M');
              const endDate = gantt.date.add(gantt.date.add(date, 3, 'month'), -1, 'day');
              return yearStr + dateToStr(date) + ' - ' + dateToStr(endDate);
            }
          },
          {
            unit: 'week',
            step: 1,
            format: (date) => {
              const dateToStr = gantt.date.date_to_str('%m-%d');
              const endDate = gantt.date.add(date, 6, 'day');
              return dateToStr(date) + ' 至 ' + dateToStr(endDate);
            }
          }
        ]
      },
      {
        name: 'month',
        scale_height: 50,
        min_column_width: 150,
        scales: [
          { unit: 'year', step: 1, format: '%Y年' },
          { unit: 'month', format: '%Y-%m' }
        ]
      }
    ]
  });
  gantt.i18n.setLocale("cn");
  gantt.config.work_time = true;
  gantt.ext.zoom.setLevel('day');
  gantt.config.add_column = false;
  gantt.config.show_progress = false;
  gantt.config.drag_resize = true;
  gantt.config.drag_links = false;
  gantt.config.order_branch = true;
  gantt.config.drag_progress = true;

  // 设置表头，新增工序列
  gantt.config.columns = [
    {
      name: "taskName",
      tree: true,
      width: '170',
      resize: true,
      label: '任务名',
      template: (obj) => obj.taskName,
      align: "left"
    },
    { name: "resource", label: "工作站", width: '100', align: "left" },
    { name: "process", label: "工序", width: '100', align: "left" }, // 新增工序列
    { name: "startTime", label: "开始时间", width: '110', align: "left" },
    { name: "endTime", label: "结束时间", width: '100', align: "left" }
  ];

  gantt.templates.grid_folder = () => "";
  gantt.templates.grid_file = () => "";

  // 设置当天标记
  const dateToStr = gantt.date.date_to_str(gantt.config.task_date);
  const today = new Date(new Date().setHours(0, 0, 0, 0));
  gantt.addMarker({
    start_date: today,
    css: "today",
    text: "今日",
    title: `Today: ${dateToStr(today)}`
  });

  // 设置颜色
  gantt.templates.task_class = (start, end, task) => task.estimate? 'gray_color' : 'red_color';
  gantt.templates.timeline_cell_class = (task, date) => 
    date.getDay() === 0 || date.getDay() === 6? "weekend-border-bottom" : "";

  // 修改任务模板，添加生产工单和完成比例信息
  gantt.templates.task_text = (start, end, task) => {
    return `${task.productionOrder} 完成比例: ${task.completionRate}%`;
  };

  gantt.config.fit_tasks = true;
  gantt.templates.quick_info_content = (start, end, task) => `
    <div>
      <h2>${task.taskName}</h2><br/>
      计划开始 : ${task.startTime}<br/>
      计划结束 : ${task.endTime}<br/>
    </div>
  `;
  gantt.templates.tooltip_text = (start, end, task) => 
    task.taskName +
    '<br/><span>开始:</span> ' + gantt.templates.tooltip_date_format(start) +
    '<br/><span>结束:</span> ' + gantt.templates.tooltip_date_format(end);

  // 双击编辑事件
  gantt.attachEvent("onTaskDblClick", (taskId) => {
    const task = gantt.getTask(taskId);
    if (task) openGanttDialog(task);
    return true;
  });

  gantt.init("gantt_here");
  fetchGanttData(); // 初始化加载甘特图数据
});
</script>

<style scoped>
.red_color {
  background: red;
}
.weekend-border-bottom {
  background: #bdbbbb;
  color: rgb(255, 255, 255) !important;
}
.blue_color {
  background: blue;
}
.gray_color {
  background: gray;
}
.gantt_cal_qi_controls,
.gantt_cal_qi_title {
  display: none;
}

.el-dialog {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 甘特图对话框样式 */
.el-date-picker {
  width: 100%;
}
</style>